package app.purchase.a571xz.com.myandroidframe.base;

import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.inject.Inject;

import app.purchase.a571xz.com.myandroidframe.R;
import app.purchase.a571xz.com.myandroidframe.base.activity.IActivityLife;
import app.purchase.a571xz.com.myandroidframe.base.activity.IBaseActivity;
import app.purchase.a571xz.com.myandroidframe.base.mvp.IPresenter;
import app.purchase.a571xz.com.myandroidframe.utils.ColorBar;
import butterknife.BindColor;
import butterknife.ButterKnife;

import static app.purchase.a571xz.com.myandroidframe.utils.SoftInputUtil.hideSoftInput;
import static app.purchase.a571xz.com.myandroidframe.utils.SoftInputUtil.isShouldHideInput;

public abstract class BaseActivity<P extends IPresenter> extends AppCompatActivity implements BaseAct, IBaseActivity {
    @BindColor(R.color.colorPrimary)
    int mColor;
    protected P mPresenter;

    protected abstract int getContentLayout();//返回页面布局id

    protected abstract void initView(Bundle savedInstanceState);//做视图相关的初始化工作

    protected abstract void initData(Bundle savedInstanceState);//做数据相关的初始化工作

    protected abstract void initEvent();//做监听事件相关的初始化工作

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getContentLayout() != 0) {
            setContentView(getContentLayout());
            ButterKnife.bind(this);
        }
        initBarColor();//初始化状态栏/导航栏颜色，需在设置了布局后再调用
        initView(savedInstanceState);
        initData(savedInstanceState);
        initEvent();
    }

    @Override
    public Resources getResources() {
        //获取到resources对象
        Resources res = super.getResources();
        //修改configuration的fontScale属性
        res.getConfiguration().fontScale = 1;
        //将修改后的值更新到metrics.scaledDensity属性上
        res.updateConfiguration(null, null);
        return res;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (isNeedTouchListen()) {   //判断当前activity是否需要edittextview的外部点击事件
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
                View v = getCurrentFocus();
                if (isShouldHideInput(v, ev)) {
                    hideSoftInput(this, v);
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void initBarColor() {
        ColorBar.newColorBuilder()
                .applyNav(true)
                .navColor(mColor).navDepth(0)
                .statusColor(mColor)
                .statusDepth(0)
                .build(this)
                .apply();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this); //友盟统计 session
        uApp_EventStatisticStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        uApp_EventStatisticEnd();
        MobclickAgent.onPause(this); //友盟统计session
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
            mPresenter = null;
        }
    }

    /**
     * 设置Android状态栏的字体颜色，状态栏为亮色的时候字体和图标是黑色，状态栏为暗色的时候字体和图标为白色
     *
     * @param dark 状态栏字体是否为深色
     */
    public void setStatusBarFontIconDark(boolean dark) {
//        // 小米MIUI
        try {
            Window window = getWindow();
            Class clazz = getWindow().getClass();
            Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            int darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            if (dark) {    //状态栏亮色且黑色字体
                extraFlagField.invoke(window, darkModeFlag, darkModeFlag);
            } else {       //清除黑色字体
                extraFlagField.invoke(window, 0, darkModeFlag);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 魅族FlymeUI
        try {
            Window window = getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (dark) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            window.setAttributes(lp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // android6.0+系统
        // 这个设置和在xml的style文件中用这个<item name="android:windowLightStatusBar">true</item>属性是一样的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (dark) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }else{
                getWindow().getDecorView().setSystemUiVisibility(View.STATUS_BAR_VISIBLE);
            }
        }
    }
}
